package controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zxf.pojo.Messages;
import com.zxf.pojo.Params;
import com.zxf.pojo.Users;
import com.zxf.service.UserService;

@Controller
@RequestMapping(value="/userRedis")
public class UserRedisController{

	@Autowired 
	private UserService userService;
    
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    
    @RequestMapping(value={"/add","/add.html"},method={RequestMethod.GET})
    public ModelAndView add(HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> map = new HashMap<String, Object>();
        //return toView("add", map);
		return null;
    }
    
    @RequestMapping(value={"/saveuser"},method={RequestMethod.POST})
    public void saveuser(Users user,HttpServletRequest request,HttpServletResponse response){
    	JSONObject obj = new JSONObject();
    	Map<String, Object> responseMap = new HashMap<String, Object>();
        Map<String,Object> map = new HashMap<String, Object>();
        UUID.randomUUID(); 
        user.setUserid(UUID.randomUUID().toString());
        user.setSignup(new Date().toString());
        userService.saveUser(user);
        Boolean flag = true;
       Users users = userService.getuser(user.getUsername().toLowerCase());
        System.out.println(obj.toString());
       // System.out.println("json2:"+json2);
        if(null != users && null!=users.getUsername() && "".equals(users.getUsername())){
        	 responseMap.put("method", "Create");
     		responseMap.put("success", "true");
     		responseMap.put("info", "新增成功！");
     		response.setContentType("text/html;charset=UTF-8");
        	
        }else{
        	responseMap.put("method", "Create");
     		responseMap.put("success", "false");
     		responseMap.put("info", "新增失败！");
     		response.setContentType("text/html;charset=UTF-8");
        	
        }
       
    }
   
    
 // 用户登录
 		@RequestMapping("/userlogin")
 			public @ResponseBody JSONObject userlogin(Users users,HttpServletRequest request, HttpServletResponse response) {
 				 JSONObject obj = new JSONObject();
 				 HttpSession session = request.getSession(); 
 				// StringBuffer toJson=new StringBuffer();//用来放json数据 
 				 JSONArray js = new JSONArray();
 				 Users users2 = new Users();
 				//得到生成的验证码  
 			     String strCode = (String) session.getAttribute("randomCode");  
 			     System.out.println("验证码:"+strCode);  
 				    //定义一个msg变量，可用于存放错误信息，然后传到前台  
 				    //用于告诉前台时候登录成功  
 				 boolean successe = false;
 				 if(!users.getCheckCode().toLowerCase().equals(strCode.toLowerCase())){
 					 obj.put("success", false);
 					 obj.put("message", "验证码错误！");
 					 return obj;
 					 
 				 }
 				 
 				 users2 = userService.getuser(users);
 				 
 				
 				 
 				if(null != users2){
 					obj.put("users", users2); 
 					obj.put("success", true);
 					
 				}
 				else{
 					obj.put("success", false);
 					 obj.put("message", "用户名或者密码错误！");
 					
 				}
 			
 				
 					// response.setHeader("Cache-Control", "no-cache");
 					// response.setContentType("text/json;charset=utf-8"); 
 					//response.getWriter().write(obj.toString());
 					// TODO Auto-generated catch block
 				//json格式化后输出
 				 System.out.println(obj.toString());
 					return obj;
 				
 			}
    
  

	@RequestMapping(value={"/userlist"})
		public @ResponseBody JSONObject userlist(Params params,String page, String limit , String start,Users users,HttpServletRequest request, HttpServletResponse response) {
		 JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据 
		 JSONArray js = new JSONArray();
		 //页码
		int pageno = Integer.parseInt(page);
		//每页数量
		int pageSize2 = Integer.parseInt(limit);
		 //int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
		 int start2 = (pageno-1)*pageSize2;
		//Map<String, Object> userlist2 =  (Map<String, Object>) userService.getUserList3(start2,Integer.parseInt(start));
	List userlist =  userService.getRedisUserList(start2,pageSize2);
	int totle = userService.getRedistotle("users");
	//System.out.println(pageno==1?pageno:(pageno-1));
	obj.put("data", js.fromObject(userlist));
	 obj.put("total", totle); //统计数量，这里写死10条
	 obj.put("success", true);
		
			// response.setHeader("Cache-Control", "no-cache");
			// response.setContentType("text/json;charset=utf-8"); 
			//response.getWriter().write(obj.toString());
			// TODO Auto-generated catch block
		//json格式化后输出
		 System.out.println(obj.toString());
				return obj;
			
		
    }
    
    @RequestMapping(value={"/{id:\\d+}/query","/{id:\\d+}/query.html"},method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView queryMember(HttpServletRequest request,HttpServletResponse response,
            @PathVariable("id")String id){
        Map<String,Object> map = new HashMap<String, Object>();
        System.out.println(id);
        Users users = this.userService.getId(Integer.parseInt(id));
        if(null!=users){
            map.put("message", "查询Id=" + id + "的用户名为:" + users.getUsername());
        }else{
            map.put("message", "没有查询到与Id=" + id + "相关的数据");
        }
        //return toView("member/message", map);
		return null;
    }
    
    @RequestMapping(value={"/{id:\\d+}/delete","/{id:\\d+}/delete.html"},method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView deleteMember(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("id")String id){
        Map<String,Object> map = new HashMap<String, Object>();
        try {
            this.userService.delete(Integer.parseInt(id));
            map.put("message", "删除Id为" + id +"的用户成功.");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "删除Id为" + id +"的用户失败, "+e.getMessage());
        }
        //return toView("member/message", map);    
		return null;
    }
    
    @RequestMapping(value={"/savemessage"},method={RequestMethod.POST})
    public void savemessage(Messages message,HttpServletRequest request,HttpServletResponse response){
    	JSONObject obj = new JSONObject();
    	Map<String, Object> responseMap = new HashMap<String, Object>();
        Map<String,Object> map = new HashMap<String, Object>();
        UUID.randomUUID(); 
        message.setId(UUID.randomUUID().toString());
        message.setPosted(new Date().toString());
        message.setUid("zxfzxc2d5a106f5-6f5e-4770-8191-7da735df0784");
        message.setLoginame("zxfzxc2");
        userService.saveMessage(message);
        Boolean flag = true;
        Messages messages = userService.getmessage(message.getId().toLowerCase());
        System.out.println(obj.toString());
       // System.out.println("json2:"+json2);
        if(null != messages && null!=messages.getId() && "".equals(messages.getId())){
        	responseMap.put("method", "Create");
     		responseMap.put("success", "true");
     		responseMap.put("info", "新增成功！");
     		response.setContentType("text/html;charset=UTF-8");
        	
        }else{
        	responseMap.put("method", "Create");
     		responseMap.put("success", "false");
     		responseMap.put("info", "新增失败！");
     		response.setContentType("text/html;charset=UTF-8");
        	
        }
       
    }
    
	@RequestMapping(value={"/messagelist"})
	public @ResponseBody JSONObject messagelist(String page, String limit , String start,Users users,HttpServletRequest request, HttpServletResponse response) {
	 JSONObject obj = new JSONObject();
	// StringBuffer toJson=new StringBuffer();//用来放json数据 
	 JSONArray js = new JSONArray();
	 //页码
	int pageno = Integer.parseInt(page);
	//每页数量
	int pageSize2 = Integer.parseInt(limit);
	 //int start2 = (Integer.parseInt(pageno)-1)*Integer.parseInt(pageSize);
	 int start2 = (pageno-1)*pageSize2;
	//Map<String, Object> userlist2 =  (Map<String, Object>) userService.getUserList3(start2,Integer.parseInt(start));
List messagelist =  userService.getRedisMessagesList(start2, pageSize2);
int totle = userService.getRedistotle("message");
//System.out.println(pageno==1?pageno:(pageno-1));
obj.put("data", js.fromObject(messagelist));
 obj.put("total", totle); //统计数量，这里写死10条
 obj.put("success", true);
	
		// response.setHeader("Cache-Control", "no-cache");
		// response.setContentType("text/json;charset=utf-8"); 
		//response.getWriter().write(obj.toString());
		// TODO Auto-generated catch block
	//json格式化后输出 
	 System.out.println(obj.toString());
			return obj;
		
	
}
    
}
